package com.ruoyi.common.utils.sso;

import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.LinkedHashMap;
import java.util.Map;


@Component
public class MyHttpSessionHolder implements HttpSessionListener {

    public static Map<String, HttpSession> sessionMap = new LinkedHashMap<String, HttpSession>();

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        HttpSession session = httpSessionEvent.getSession();
        sessionMap.put(session.getId(), session);
    }


    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        HttpSession session = httpSessionEvent.getSession();
        sessionMap.remove(session.getId());
    }


    public static HttpSession getSession(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if(session != null) {
            return session;
        }
        String token = request.getHeader("JSESSIONID");
        if(token == null) {
            token = request.getHeader("token");
            if(token == null) {
                token = request.getParameter("token");
            }
        }
        HttpSession session2 = sessionMap.get(token);
        if(session2 != null) {
            return session2;
        }
        return request.getSession();
    }


}
